package com.yangyuhao.haowuyoupin;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDialog;
import com.yangyuhao.haowuyoupin.db.UserDao;
import com.yangyuhao.haowuyoupin.model.User;

public class SettingsActivity extends AppCompatActivity {
    private UserDao userDao;
    private User currentUser;
    private TextView tvNickname;
    private ImageView ivAvatar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        // 初始化数据库操作对象
        userDao = new UserDao(this);
        
        // 初始化视图
        tvNickname = findViewById(R.id.tv_nickname);
        ivAvatar = findViewById(R.id.iv_avatar);

        // 加载用户数据
        loadUserData();

        // 返回按钮点击事件
        findViewById(R.id.btn_back).setOnClickListener(v -> finish());

        // 头像设置点击事件
        findViewById(R.id.avatar_setting).setOnClickListener(v -> {
            if (currentUser != null) {
                // TODO: 实现头像修改逻辑
                Toast.makeText(this, "修改头像", Toast.LENGTH_SHORT).show();
            }
        });

        // 昵称设置点击事件
        findViewById(R.id.nickname_setting).setOnClickListener(v -> {
            if (currentUser != null) {
                // 创建修改昵称的对话框
                AppCompatDialog dialog = new AppCompatDialog(this);
                dialog.supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(R.layout.dialog_change_nickname);
                
                // 设置对话框宽度和背景
                Window window = dialog.getWindow();
                if (window != null) {
                    window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    WindowManager.LayoutParams params = window.getAttributes();
                    params.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.8);
                    window.setAttributes(params);
                }

                // 获取对话框中的控件
                EditText etNewNickname = dialog.findViewById(R.id.et_new_nickname);
                etNewNickname.setText(currentUser.getNickname()); // 显示当前昵称
                etNewNickname.setSelection(etNewNickname.length()); // 光标移到末尾

                // 取消按钮点击事件
                dialog.findViewById(R.id.btn_cancel).setOnClickListener(view -> dialog.dismiss());
                
                // 确认按钮点击事件
                dialog.findViewById(R.id.btn_confirm).setOnClickListener(view -> {
                    String newNickname = etNewNickname.getText().toString().trim();
                    if (TextUtils.isEmpty(newNickname)) {
                        Toast.makeText(this, "昵称不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 更新用户昵称
                    currentUser.setNickname(newNickname);
                    if (userDao.updateUser(currentUser)) {
                        Toast.makeText(this, "昵称修改成功", Toast.LENGTH_SHORT).show();
                        tvNickname.setText(newNickname);
                        dialog.dismiss();
                    } else {
                        Toast.makeText(this, "昵称修改失败", Toast.LENGTH_SHORT).show();
                    }
                });

                dialog.show();
            }
        });

        // 通知设置点击事件
        findViewById(R.id.notification_setting).setOnClickListener(v -> 
            Toast.makeText(this, "通知设置", Toast.LENGTH_SHORT).show());

        // 关于我们点击事件
        findViewById(R.id.about_us).setOnClickListener(v -> 
            Toast.makeText(this, "关于我们", Toast.LENGTH_SHORT).show());

        // 修改密码点击事件
        findViewById(R.id.btn_change_password).setOnClickListener(v -> {
            if (currentUser != null) {
                // 创建修改密码的对话框
                AppCompatDialog dialog = new AppCompatDialog(this);
                dialog.supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(R.layout.dialog_change_password);
                
                // 设置对话框宽度和背景
                Window window = dialog.getWindow();
                if (window != null) {
                    window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    WindowManager.LayoutParams params = window.getAttributes();
                    params.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.8);
                    window.setAttributes(params);
                }

                // 获取对话框中的控件
                EditText etOldPassword = dialog.findViewById(R.id.et_old_password);
                EditText etNewPassword = dialog.findViewById(R.id.et_new_password);
                EditText etConfirmPassword = dialog.findViewById(R.id.et_confirm_password);

                // 取消按钮点击事件
                dialog.findViewById(R.id.btn_cancel).setOnClickListener(view -> dialog.dismiss());
                
                // 确认按钮点击事件
                dialog.findViewById(R.id.btn_confirm).setOnClickListener(view -> {
                    String oldPassword = etOldPassword.getText().toString().trim();
                    String newPassword = etNewPassword.getText().toString().trim();
                    String confirmPassword = etConfirmPassword.getText().toString().trim();

                    if (TextUtils.isEmpty(oldPassword)) {
                        Toast.makeText(this, "请输入原密码", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(newPassword)) {
                        Toast.makeText(this, "请输入新密码", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(confirmPassword)) {
                        Toast.makeText(this, "请确认新密码", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (!newPassword.equals(confirmPassword)) {
                        Toast.makeText(this, "两次输入的新密码不一致", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    // 更新密码
                    if (userDao.updatePassword(currentUser.getAccount(), oldPassword, newPassword)) {
                        Toast.makeText(this, "密码修改成功", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    } else {
                        Toast.makeText(this, "原密码错误", Toast.LENGTH_SHORT).show();
                    }
                });

                dialog.show();
            }
        });

        // 退出登录点击事件
        findViewById(R.id.btn_logout).setOnClickListener(v -> {
            // 创建自定义对话框
            AppCompatDialog dialog = new AppCompatDialog(this);
            dialog.supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.dialog_logout);
            
            // 设置对话框宽度和背景
            Window window = dialog.getWindow();
            if (window != null) {
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                WindowManager.LayoutParams params = window.getAttributes();
                params.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.8);
                window.setAttributes(params);
            }

            // 设置按钮点击事件
            dialog.findViewById(R.id.btn_cancel).setOnClickListener(view -> dialog.dismiss());
            
            dialog.findViewById(R.id.btn_confirm).setOnClickListener(view -> {
                // 更新数据库中的登录状态
                UserDao userDao = new UserDao(this);
                User currentUser = userDao.getCurrentUser();
                if (currentUser != null) {
                    userDao.updateLoginStatus(currentUser.getAccount(), false);
                }
                
                Toast.makeText(this, "已退出登录", Toast.LENGTH_SHORT).show();
                // 返回到登录页面
                Intent intent = new Intent(this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
                dialog.dismiss();
            });

            dialog.show();
        });
    }

    private void loadUserData() {
        currentUser = userDao.getCurrentUser();
        if (currentUser != null) {
            // 设置昵称
            tvNickname.setText(currentUser.getNickname());
            
            // TODO: 设置头像
            // 如果有头像数据，可以使用类似 Glide 的图片加载库来加载头像
            // Glide.with(this).load(currentUser.getAvatarUrl()).into(ivAvatar);
        } else {
            // 如果没有登录用户，返回登录页面
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 每次页面重新���示时刷新用户数据
        loadUserData();
    }
} 